<template>
  <div id="">
    <!--滑动区域-->
		<div id="mescroll" class="mescroll" style="position:fixed; top:50px;bottom:0;height:auto;">
			<!--展示上拉加载的数据列表-->
    <ul class="leaseListDiv" id="dataList" style="margin-bottom:0;">
      <li v-for="(items,index) in pdlist" :key="items.key">
        <p class="leaseTit">
          <span>{{items.title}}</span>
          <em class="signed" v-if="items.state==2">已签约</em>
          <em class="tuiRent" v-else-if="items.state==16">已退租</em>
          <em class="waitSign" v-else-if="items.state==1">待签约</em>
          <!-- 1 待签约 2已签约  4.租约快到期（到期前一个月）8 租约已到期   16已退租 -->
        </p>
        <div class="houseDiv">
          <!-- <img :src="items.housePic" alt="" class="houseImg"> -->
          <div class="houseImg" :style="{backgroundImage:'url(' + items.housePic + ')'}">

          </div>
          <div class="houseCon">
            <span class="title">{{items.title}}</span>
            <p class="houseAddr">
              <img src="@/assets/images/addr@2x.png" alt="" width="10">
              {{items.address}}
            </p>
            <p class="">租期 {{setRentTime(index)}}</p>
          </div>
        </div>
        <div class="btnBox" v-if="items.state==2">
          <span>
          <button type="button" name="button" class="grayBtn" @click="houseRetire(index)">退租</button>
          </span>
          <span>
          <button type="button" name="button" class="grayBtn" @click="houseSublet(index)">转租</button>
          </span>
          <span></span>
          <span>
          <button type="button" name="button" class="inlineBtn" @click="toContact(index)">查看电子合同</button>
          </span>
        </div>
        <div class="btnBox" v-if="items.state==4">
          <span>
          <button type="button" name="button" class="grayBtn" @click="houseRetire(index)">退租</button>
          </span>
          <span>
          <button type="button" name="button" class="grayBtn" @click="houseSublet(index)">转租</button>
          </span>
          <span>
          <button type="button" name="button" class="btn" @click="continueRent(index)">续租</button>
          </span>
          <span>
          <button type="button" name="button" class="inlineBtn" @click="toContact(index)">查看电子合同</button>
          </span>
        </div>
        <div class="btnBox" v-else-if="items.state==16">
          <!-- 并发的退租房源没有对应的退租id，也就没有退租信息，也没有合同信息 -->
          <span></span>
          <span></span>
          <span>
          <button type="button" name="button" class="btn" @click="retireRentcon(index)" v-if="items.exitId">退租信息</button>
          </span>
          <span>
          <button type="button" name="button" class="inlineBtn" @click="toContact(index)" v-if="items.exitId">查看电子合同</button>
          </span>
        </div>
        <div class="btnBox" v-else-if="items.state==1">
          <span></span>
          <span></span>
          <span></span>
          <span>
          <button type="button" name="button" class="inlineBtn" @click="continueContact(index)">签约</button>
          </span>
        </div>
      </li>
    </ul>
  </div>
  </div>
</template>
<script>
import MeScroll from 'mescroll.js';
import { timestampToTime } from '@/util/util.js';
import { Toast,MessageBox } from 'mint-ui';
import {reLoginWX} from '@/util/util.js';
export default {
  name: "",
  data: () => ({
    mescroll: null,
		pdlist: [],
    subletPayDeposit:0,   //退租、转租产生的费用
    dataLength:0,   //数据长度
  }),
  methods: {
    //上拉回调 page = {num:1, size:10}; num:当前页 ,默认从1开始; size:每页数据条数,默认10
		upCallback: function(page) {
			//联网加载数据
			var self = this;
			self.getListDataFromNet(page.num, page.size, function(curPageData) {
				//curPageData=[]; //打开本行注释,可演示列表无任何数据empty的配置

				//如果是第一页需手动制空列表 (代替clearId和clearEmptyId的配置)
				if(page.num == 1) self.pdlist = [];

				//更新列表数据
				self.pdlist = self.pdlist.concat(curPageData);

				//联网成功的回调,隐藏下拉刷新和上拉加载的状态;
				//mescroll会根据传的参数,自动判断列表如果无任何数据,则提示空;列表无下一页数据,则提示无更多数据;
				console.log("page.num="+page.num+", page.size="+page.size+", curPageData.length="+curPageData.length+", self.pdlist.length==" + self.pdlist.length);
				//方法四 (不推荐),会存在一个小问题:比如列表共有20条数据,每页加载10条,共2页.如果只根据当前页的数据个数判断,则需翻到第三页才会知道无更多数据,如果传了hasNext,则翻到第二页即可显示无更多数据.
				self.mescroll.endSuccess(self.dataLength);

			}, function() {
				//联网失败的回调,隐藏下拉刷新和上拉加载的状态;
				self.mescroll.endErr();
			});
		},
    getListDataFromNet(pageNum,pageSize,successCallback,errorCallback) {
      let that =  this;
        this.$ajax.get(configUrl.MYRENTHOUSELIST_URL, {
					params: {
            rentType:1,
						currentPage: pageNum, //页码
						showCount: pageSize //每页长度
					}
				})
				.then((response) => {
          console.log(response);
          console.log(response.data.subletPayDeposit);
					var data=response.data.dataList; // 模拟数据: ../res/pdlist1.js
          that.dataLength = data.length;
          that.subletPayDeposit = (response.data.subletPayDeposit)/100;
                	successCallback&&successCallback(data);//成功回调
				})
				.catch((error) => {
					errorCallback&&errorCallback()//失败回调
				});
		},
    // 租期
    setRentTime(index) {
      let that = this;
      let dataList = that.pdlist[index];
      let beginDate = dataList.rentBeginDate;
      let endDate = dataList.rentEndDate;
      return timestampToTime(beginDate) + '-' +timestampToTime(endDate);
    },
    // 退租
    houseRetire(index) {
      let that = this;
      let dataList = that.pdlist[index];
      MessageBox.confirm('确认是否退租').then(action=>{
        let contactParam = {
          contractId:dataList.contractId
        }
        network.post(configUrl.USERRETIRERENT_URL,contactParam,function (res) {
          console.log(res);
          if(res.code==401) {
            reLoginWX();
          }else{
            MessageBox.alert('退租申请成功，请耐心等待后台审核的提示').then(action =>{
              that.$router.go(0);
            });

          }
        },function (err) {
          console.log(err);
        });
      })
      .catch((error) => {
        console.log(error);
      });
    },
    // 转租
    houseSublet(index) {
      let that = this;
      let dataList = that.pdlist[index];
      let subletPayDeposit = that.subletPayDeposit;
      MessageBox.confirm('确认是否转租，转租会产生'+subletPayDeposit+'元转租费用').then(action=>{
        let contactParam = {
          contractId:dataList.contractId
        }
        network.post(configUrl.USERSUBLETHOUSE_URL,contactParam,function (res) {
          console.log(res);
          if(res.code==401) {
            reLoginWX();
          }else{
            MessageBox.alert('转租申请成功，请耐心等待后台审核的提示').then(action =>{
              that.$router.go(0);
            });
            that.$router.go(0);
          }
        },function (err) {
          console.log(err);
        });
      }).catch(error=>{
        console.log(error);
      })
    },
    // 续租
    continueRent(index) {
      let that = this;
      let dataList = that.pdlist[index];
      MessageBox.confirm('确认是否续租，续租将对当前租约进行优先结算，结算后签约新合同').then(action=>{
        let contactParam = {
          contractId:dataList.contractId
        }
        network.post(configUrl.CONTINUERENT_URL,contactParam,function (res) {
          console.log(res);
          if(res.code==401) {
            reLoginWX();
          }else{
            MessageBox.alert('续租申请提交成功，请耐心等待后台审核').then(action =>{
              that.$router.go(0);
            });
          }
        },function (err) {
          console.log(err);
        });
      }).catch(error=>{
        console.log(error);
      })
    },
    // 继续签约
    continueContact(index) {
      let that = this;
      let dataList = that.pdlist[index];
      let contractParam = {
        contractId:dataList.contractId
      }
      network.post(configUrl.CONTACTONLINE_URL,contractParam,function(res){
        console.log(res);
        window.location.href = res.data.url;
      },function(err){
        console.log(err);
      });
    },
    // 查看电子合同
    toContact(index) {
      let that = this;
      let dataList = that.pdlist[index];
      if (dataList.state==1) {  //待签约
        Toast('该房源还未签约，没有电子合同');
      }else {
        window.location.href = dataList.electContract;  //电子合同地址
      }
    },
    // 查看退租信息
    retireRentcon(index) {
      let exitId = this.pdlist[index].exitId;
      console.log(exitId);
      this.$router.push({path:'/tuiRentBill',query:{exitId:exitId}});
    }
  },
  mounted() {
    //do something after mounting vue instance
    var self = this;
		self.mescroll = new MeScroll("mescroll", { //请至少在vue的mounted生命周期初始化mescroll,以确保您配置的id能够被找到
			up: {
				callback: self.upCallback, //上拉回调
				//以下参数可删除,不配置
				isBounce: false, //此处禁止ios回弹,解析(务必认真阅读,特别是最后一点): http://www.mescroll.com/qa.html#q10
				//page:{size:8}, //可配置每页8条数据,默认10
				toTop:{ //配置回到顶部按钮
					src : "../res/img/mescroll-totop.png", //默认滚动到1000px显示,可配置offset修改
					//html: null, //html标签内容,默认null; 如果同时设置了src,则优先取src
					//offset : 1000
				},
				empty:{ //配置列表无任何数据的提示
					warpId:"dataList",
					icon : require("@/assets/images/attention@2x.png") ,
//						  	tip : "亲,暂无相关数据哦~" ,
//						  	btntext : "去逛逛 >" ,
//						  	btnClick : function() {
//						  		alert("点击了去逛逛按钮");
//						  	}
				},
			}
		});
  }
    //房源状态 1空置  2已租 4租约快到期（到期前一个月） 8租约已到期  16续租待确认  32退租待处理  64转租中'

    // 租约关联房源  如果是2 ，4就是已签约，8 已退租，16 待签约
//     房源状态 1空置  2已租
// 租约状态 1.租约快到期（到期前一个月） 2租约已到期  3续租待确认  4退租待处理  5转租中  6 待签约  7已签约   8已退租  9待签约

}
</script>
<style lang="scss" scoped>

.leaseListDiv{
  background: #f5f5f5;
  li{
    background: white;
    padding:10px;
    margin-bottom: 10px;
  }
}
.leaseTit{
  @include flex;
  justify-content: space-between;
  span{
    width: 80%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  em{
    &.signed{
      color: $greenColor;
    }
    &.tuiRent{
      color:$blueColor;
    }
    &.waitSign{
      color: $redColor;
    }
  }
}
.houseDiv{
  @include flex;
  padding: 10px 0;
  .houseImg{
    border-radius: 4px;
    width: 100px;
    height: 80px;
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
  }
  .houseCon{
    margin-left: 10px;
    @include flexcell;
    @include flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: space-between;
    // height: 80px;
  }
  .title{
    font-size: 16px;
    font-weight: 550;
  }
  .houseAddr{
    font-size: 10px;
    margin: 4px 0;
    height: 20px;
    width: 90%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

}
.btnBox{
  @include flex;
  span{
    @include flexcell;
    margin-right: 10px;
    height: 2.4rem;
    button{
      width: 96%;
      padding-left: 2%;
      padding-right: 2%;
    }
    &:last-child{
      flex:2;
      margin-right: 0;
    }
  }
}
.keywords{
  span{
    margin-right: 6px;
    margin-bottom: 4px;
    display: inline-block;
    background: #eef0f4;
    color: #8996a2;
    border-radius: 4px;
    padding:2px 6px;
    font-size: 10px;
  }
}
</style>
